<template>
  <div class="repair-container">
    <h2>房屋维修管理</h2>

    <!-- 维修申请表单 -->
    <div class="repair-form">
      <el-form :model="repairForm" label-width="100px">
        <el-form-item label="房屋编号">
          <el-input v-model="repairForm.houseId" placeholder="请输入房屋编号"></el-input>
        </el-form-item>
        <el-form-item label="维修类型">
          <el-select v-model="repairForm.type" placeholder="请选择维修类型">
            <el-option label="水电维修" value="水电维修"></el-option>
            <el-option label="家具维修" value="家具维修"></el-option>
            <el-option label="墙面维修" value="墙面维修"></el-option>
            <el-option label="管道维修" value="管道维修"></el-option>
            <el-option label="其他维修" value="其他维修"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述">
          <el-input
              type="textarea"
              v-model="repairForm.description"
              placeholder="请详细描述问题"
              :rows="4">
          </el-input>
        </el-form-item>
        <el-form-item label="紧急程度">
          <el-radio-group v-model="repairForm.urgency">
            <el-radio-button label="高"></el-radio-button>
            <el-radio-button label="中"></el-radio-button>
            <el-radio-button label="低"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitRepair">提交申请</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 维修评价统计 -->
    <div class="rating-stats">
      <h3>维修评价统计</h3>
      <div class="stats-cards">
        <el-card class="stat-card">
          <div class="stat-title">总维修次数</div>
          <div class="stat-value">{{ stats.totalRepairs }}</div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-title">好评率</div>
          <div class="stat-value">{{ stats.goodRate }}%</div>
          <el-progress
              :percentage="stats.goodRate"
              :color="getRateColor(stats.goodRate)"
              :show-text="false">
          </el-progress>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-title">平均评分</div>
          <div class="stat-value">{{ stats.avgRating.toFixed(1) }}</div>
          <el-rate
              v-model="stats.avgRating"
              disabled
              show-score
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
          </el-rate>
        </el-card>
      </div>
    </div>

    <!-- 维修评论弹幕 -->
    <div class="danmu-container">
      <h3>用户评价弹幕</h3>
      <div class="danmu-box" ref="danmuBox">
        <div
            v-for="(comment, index) in visibleComments"
            :key="index"
            class="danmu-item"
            :style="{
            top: `${comment.top}px`,
            left: `${comment.left}px`,
            color: getRandomColor(),
            animationDuration: `${comment.duration}s`
          }">
          {{ comment.content }}
          <el-rate
              v-model="comment.rating"
              disabled
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
          </el-rate>
        </div>
      </div>
    </div>

    <!-- 维修记录列表 -->
    <div class="repair-list">
      <h3>维修记录</h3>
      <el-table :data="repairRecords" border style="width: 100%">
        <el-table-column prop="id" label="维修编号" width="120"></el-table-column>
        <el-table-column prop="houseId" label="房屋编号" width="120"></el-table-column>
        <el-table-column prop="type" label="维修类型" width="120"></el-table-column>
        <el-table-column prop="urgency" label="紧急程度" width="120">
          <template #default="{row}">
            <el-tag :type="getUrgencyTagType(row.urgency)">
              {{ row.urgency }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{row}">
            <el-tag :type="getStatusTagType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180"></el-table-column>
        <el-table-column prop="rating" label="评分" width="150">
          <template #default="{row}">
            <el-rate
                v-model="row.rating"
                disabled
                show-score
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
            </el-rate>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button size="small" @click="showCommentDialog(row)">评价</el-button>
            <el-button size="small" type="warning" @click="showDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 评价对话框 -->
    <el-dialog title="维修评价" v-model="commentDialogVisible" width="50%">
      <el-form :model="commentForm" label-width="80px">
        <el-form-item label="维修编号">
          <el-input v-model="currentRepair.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="评分" required>
          <el-rate
              v-model="commentForm.rating"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
          </el-rate>
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input
              type="textarea"
              v-model="commentForm.content"
              placeholder="请输入评价内容"
              :rows="4">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitComment">提交评价</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 维修详情对话框 -->
    <el-dialog title="维修详情" v-model="detailDialogVisible" width="70%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="维修编号">{{ currentRepair.id }}</el-descriptions-item>
        <el-descriptions-item label="房屋编号">{{ currentRepair.houseId }}</el-descriptions-item>
        <el-descriptions-item label="维修类型">{{ currentRepair.type }}</el-descriptions-item>
        <el-descriptions-item label="紧急程度">
          <el-tag :type="getUrgencyTagType(currentRepair.urgency)">
            {{ currentRepair.urgency }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="问题描述">{{ currentRepair.description }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentRepair.status)">
            {{ currentRepair.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentRepair.createTime }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ currentRepair.completeTime || '未完成' }}</el-descriptions-item>
        <el-descriptions-item label="维修人员">{{ currentRepair.repairman || '未分配' }}</el-descriptions-item>
        <el-descriptions-item label="评分" v-if="currentRepair.rating > 0">
          <el-rate
              v-model="currentRepair.rating"
              disabled
              show-score
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
          </el-rate>
        </el-descriptions-item>
        <el-descriptions-item label="评价内容" :span="2" v-if="currentRepair.comment">
          {{ currentRepair.comment }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'RepairManagement',
  data() {
    // 生成模拟维修数据
    const generateRepairRecords = () => {
      const records = [];
      const types = ['水电维修', '家具维修', '墙面维修', '管道维修', '其他维修'];
      const statuses = ['待处理', '处理中', '已完成', '已取消'];
      const repairmen = ['张三', '李四', '王五', '赵六', '钱七'];

      for (let i = 1; i <= 30; i++) {
        const id = `R2023${String(i).padStart(4, '0')}`;
        const houseId = `H${Math.floor(1000 + Math.random() * 9000)}`;
        const type = types[Math.floor(Math.random() * types.length)];
        const urgency = ['高', '中', '低'][Math.floor(Math.random() * 3)];
        const status = statuses[Math.floor(Math.random() * statuses.length)];
        const rating = status === '已完成' ? Math.floor(1 + Math.random() * 5) : 0;
        const comment = rating > 0 ? [
          '师傅很专业，解决问题很快',
          '服务态度很好，点个赞',
          '维修质量不错，价格合理',
          '响应速度很快，很满意',
          '问题没有完全解决，还需要改进',
          '维修人员迟到了一会儿，但技术不错',
          '非常满意，下次还会选择'
        ][Math.floor(Math.random() * 7)] : '';

        const createDate = new Date();
        createDate.setDate(createDate.getDate() - Math.floor(Math.random() * 30));

        let completeDate = null;
        if (status === '已完成') {
          completeDate = new Date(createDate);
          completeDate.setDate(completeDate.getDate() + Math.floor(1 + Math.random() * 3));
        }

        records.push({
          id,
          houseId,
          type,
          description: `${type}问题，需要尽快处理`,
          urgency,
          status,
          repairman: status !== '待处理' ? repairmen[Math.floor(Math.random() * repairmen.length)] : null,
          createTime: createDate.toLocaleString('zh-CN'),
          completeTime: completeDate ? completeDate.toLocaleString('zh-CN') : null,
          rating,
          comment
        });
      }
      return records;
    };

    const repairRecords = generateRepairRecords();

    // 计算统计信息
    const calculateStats = (records) => {
      const completed = records.filter(r => r.status === '已完成');
      const total = completed.length;
      const good = completed.filter(r => r.rating >= 4).length;
      const avgRating = completed.length > 0 ?
          completed.reduce((sum, r) => sum + r.rating, 0) / completed.length : 0;

      return {
        totalRepairs: records.length,
        completedRepairs: total,
        goodRate: total > 0 ? Math.round((good / total) * 100) : 0,
        avgRating
      };
    };

    // 生成弹幕评论
    const generateDanmuComments = (records) => {
      return records
          .filter(r => r.rating > 0)
          .map(r => ({
            id: r.id,
            content: r.comment,
            rating: r.rating,
            top: Math.random() * 200,
            left: Math.random() * 800,
            duration: 10 + Math.random() * 20
          }));
    };

    return {
      repairForm: {
        houseId: '',
        type: '',
        description: '',
        urgency: '中'
      },
      repairRecords,
      stats: calculateStats(repairRecords),
      danmuComments: generateDanmuComments(repairRecords),
      visibleComments: [],
      currentRepair: {},
      commentDialogVisible: false,
      detailDialogVisible: false,
      commentForm: {
        rating: 5,
        content: ''
      },
      danmuTimer: null
    };
  },
  mounted() {
    this.startDanmu();
  },
  beforeUnmount() {
    this.stopDanmu();
  },
  methods: {
    submitRepair() {
      if (!this.repairForm.houseId) {
        this.$message.error('请输入房屋编号');
        return;
      }
      if (!this.repairForm.type) {
        this.$message.error('请选择维修类型');
        return;
      }
      if (!this.repairForm.description) {
        this.$message.error('请输入问题描述');
        return;
      }

      // 生成维修记录
      const id = `R${new Date().getFullYear()}${String(this.repairRecords.length + 1).padStart(4, '0')}`;
      const newRepair = {
        id,
        ...this.repairForm,
        status: '待处理',
        createTime: new Date().toLocaleString('zh-CN'),
        rating: 0,
        comment: ''
      };

      this.repairRecords.unshift(newRepair);
      this.stats = this.calculateStats(this.repairRecords);
      this.$message.success('维修申请已提交！');
      this.resetForm();
    },
    resetForm() {
      this.repairForm = {
        houseId: '',
        type: '',
        description: '',
        urgency: '中'
      };
    },
    showCommentDialog(row) {
      if (row.status !== '已完成') {
        this.$message.warning('只有已完成的维修才能评价');
        return;
      }
      this.currentRepair = { ...row };
      this.commentForm = {
        rating: row.rating || 5,
        content: row.comment || ''
      };
      this.commentDialogVisible = true;
    },
    submitComment() {
      if (this.commentForm.rating < 1) {
        this.$message.error('请选择评分');
        return;
      }

      const index = this.repairRecords.findIndex(r => r.id === this.currentRepair.id);
      if (index !== -1) {
        this.repairRecords[index].rating = this.commentForm.rating;
        this.repairRecords[index].comment = this.commentForm.content;

        // 更新弹幕
        this.danmuComments = this.generateDanmuComments(this.repairRecords);

        // 更新统计
        this.stats = this.calculateStats(this.repairRecords);

        this.$message.success('评价已提交！');
        this.commentDialogVisible = false;
      }
    },
    showDetail(row) {
      this.currentRepair = { ...row };
      this.detailDialogVisible = true;
    },
    getUrgencyTagType(urgency) {
      switch(urgency) {
        case '高': return 'danger';
        case '中': return 'warning';
        case '低': return 'success';
        default: return '';
      }
    },
    getStatusTagType(status) {
      switch(status) {
        case '已完成': return 'success';
        case '处理中': return 'primary';
        case '待处理': return 'info';
        case '已取消': return 'danger';
        default: return '';
      }
    },
    getRateColor(rate) {
      if (rate >= 80) return '#67C23A';
      if (rate >= 60) return '#E6A23C';
      return '#F56C6C';
    },
    getRandomColor() {
      const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#B37FEB', '#FF85C0'];
      return colors[Math.floor(Math.random() * colors.length)];
    },
    startDanmu() {
      this.updateDanmu();
      this.danmuTimer = setInterval(this.updateDanmu, 3000);
    },
    stopDanmu() {
      if (this.danmuTimer) {
        clearInterval(this.danmuTimer);
      }
    },
    updateDanmu() {
      if (this.danmuComments.length === 0) return;

      const count = Math.min(5, this.danmuComments.length);
      const newComments = [];

      for (let i = 0; i < count; i++) {
        const randomIndex = Math.floor(Math.random() * this.danmuComments.length);
        const comment = { ...this.danmuComments[randomIndex] };
        comment.top = Math.random() * 200;
        comment.left = Math.random() * 800;
        comment.duration = 10 + Math.random() * 20;
        newComments.push(comment);
      }

      this.visibleComments = newComments;
    },
    calculateStats(records) {
      const completed = records.filter(r => r.status === '已完成');
      const total = completed.length;
      const good = completed.filter(r => r.rating >= 4).length;
      const avgRating = completed.length > 0 ?
          completed.reduce((sum, r) => sum + r.rating, 0) / completed.length : 0;

      return {
        totalRepairs: records.length,
        completedRepairs: total,
        goodRate: total > 0 ? Math.round((good / total) * 100) : 0,
        avgRating
      };
    },
    generateDanmuComments(records) {
      return records
          .filter(r => r.rating > 0 && r.comment)
          .map(r => ({
            id: r.id,
            content: r.comment,
            rating: r.rating,
            top: Math.random() * 200,
            left: Math.random() * 800,
            duration: 10 + Math.random() * 20
          }));
    }
  }
}
</script>

<style scoped>

.repair-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.repair-form {
  background: #ffffff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.rating-stats {
  background: #ffffff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.stats-cards {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.stat-card {
  flex: 1;
  margin: 0 10px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.danmu-container {
  background: #ffffff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.danmu-box {
  position: relative;
  height: 250px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 15px;
}

.danmu-item {
  position: absolute;
  white-space: nowrap;
  font-size: 16px;
  font-weight: bold;
  animation: danmu linear;
  display: flex;
  align-items: center;
  gap: 10px;
}

@keyframes danmu {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(-100%);
  }
}
.repair-list {
  background: #ffffff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.repair-container {
  position: relative;
  min-height: 100vh;
  padding: 20px;
}



.repair-form,
.rating-stats,
.danmu-container,
.repair-list {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
</style>